import {
  AlipayCircleOutlined,
  LockOutlined,
  MobileOutlined,
  ReloadOutlined,
  TaobaoCircleOutlined,
  UserOutlined,
  WeiboCircleOutlined,
} from '@ant-design/icons';
import {
  LoginForm,
  ProFormCaptcha,
  ProFormCheckbox,
  ProFormText,
} from '@ant-design/pro-components';
import {
  FormattedMessage,
  Helmet,
  SelectLang,
  useIntl,
  useModel,
} from '@umijs/max';
import { Alert, App, Tabs, message, Form } from 'antd';
import { createStyles } from 'antd-style';
import React, { useState, useEffect, useRef } from 'react';
import { flushSync } from 'react-dom';
import { Footer } from '@/components';
import { login } from '@/services/ant-design-pro/api';
import { getFakeCaptcha } from '@/services/ant-design-pro/login';
import Settings from '../../../../config/defaultSettings';
import './index.css'
// 导入图片
import background from '@/assets/background.jpg';
import circle from '@/assets/circle.png';


// 生成随机验证码
const generateCaptcha = () => {
  const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  let captcha = '';
  for (let i = 0; i < 4; i++) {
    captcha += chars.charAt(Math.floor(Math.random() * chars.length));
  }
  return captcha;
};

// 绘制验证码图片
const drawCaptcha = (text: string) => {
  const canvas = document.createElement('canvas');
  const ctx = canvas.getContext('2d');
  if (!ctx) return '';

  canvas.width = 120;
  canvas.height = 40;

  // 背景色
  ctx.fillStyle = '#f5f5f5';
  ctx.fillRect(0, 0, canvas.width, canvas.height);

  // 干扰线
  for (let i = 0; i < 5; i++) {
    ctx.strokeStyle = `rgb(${Math.random() * 255},${Math.random() * 255},${Math.random() * 255})`;
    ctx.beginPath();
    ctx.moveTo(Math.random() * canvas.width, Math.random() * canvas.height);
    ctx.lineTo(Math.random() * canvas.width, Math.random() * canvas.height);
    ctx.stroke();
  }

  // 干扰点
  for (let i = 0; i < 30; i++) {
    ctx.fillStyle = `rgb(${Math.random() * 255},${Math.random() * 255},${Math.random() * 255})`;
    ctx.beginPath();
    ctx.arc(Math.random() * canvas.width, Math.random() * canvas.height, 1, 0, 2 * Math.PI);
    ctx.fill();
  }

  // 绘制文字
  ctx.font = 'bold 24px Arial';
  ctx.textAlign = 'center';
  ctx.textBaseline = 'middle';

  // 每个字符不同颜色和旋转角度
  text.split('').forEach((char, i) => {
    ctx.fillStyle = `rgb(${Math.random() * 100 + 50},${Math.random() * 100 + 50},${Math.random() * 100 + 50})`;
    ctx.save();
    ctx.translate(25 + i * 20, canvas.height / 2);
    ctx.rotate((Math.random() - 0.5) * 0.4);
    ctx.fillText(char, 0, 0);
    ctx.restore();
  });

  return canvas.toDataURL('image/png');
};

const useStyles = createStyles(({ token }) => {
  return {
    action: {
      marginLeft: '8px',
      color: 'rgba(0, 0, 0, 0.2)',
      fontSize: '24px',
      verticalAlign: 'middle',
      cursor: 'pointer',
      transition: 'color 0.3s',
      '&:hover': {
        color: token.colorPrimaryActive,
      },
    },
    lang: {
      width: 42,
      height: 42,
      lineHeight: '42px',
      position: 'fixed',
      right: 16,
      borderRadius: token.borderRadius,
      ':hover': {
        backgroundColor: token.colorBgTextHover,
      },
    },
    container: {
      display: 'flex',
      flexDirection: 'column',
      height: '100vh',
      overflow: 'auto',
    },
    captchaContainer: {
      display: 'flex',
      gap: 8,
      alignItems: 'center',
    },
    captchaImage: {
      width: 120,
      height: 38,
      cursor: 'pointer',
      borderRadius: 4,
      marginBottom: 24,
    },
    reloadIcon: {
      marginLeft: 8,
      color: token.colorTextSecondary,
      cursor: 'pointer',
      '&:hover': {
        color: token.colorPrimary,
      },
    },
  };
});

const ActionIcons = () => {
  const { styles } = useStyles();

  return (
    <>
      <AlipayCircleOutlined
        key="AlipayCircleOutlined"
        className={styles.action}
      />
      <TaobaoCircleOutlined
        key="TaobaoCircleOutlined"
        className={styles.action}
      />
      <WeiboCircleOutlined
        key="WeiboCircleOutlined"
        className={styles.action}
      />
    </>
  );
};

const Lang = () => {
  const { styles } = useStyles();

  return (
    <div className={styles.lang} data-lang>
      {/* {SelectLang && <SelectLang />} */}
    </div>
  );
};

const LoginMessage: React.FC<{
  content: string;
}> = ({ content }) => {
  return (
    <Alert
      style={{
        marginBottom: 24,
      }}
      message={content}
      type="error"
      showIcon
    />
  );
};

const Login: React.FC = () => {
  const [userLoginState, setUserLoginState] = useState<API.LoginResult>({});
  const [type, setType] = useState<string>('account');
  const [captchaText, setCaptchaText] = useState('');
  const [captchaImage, setCaptchaImage] = useState('');
  const [captchaError, setCaptchaError] = useState('');
  const { initialState, setInitialState } = useModel('@@initialState');
  const { styles } = useStyles();
  const { message } = App.useApp();
  const intl = useIntl();
  const [form] = Form.useForm();
  // 用于账号输入框的引用
  const usernameInputRef = useRef<HTMLInputElement>(null);

  // 初始化验证码并设置输入框聚焦
  useEffect(() => {
    refreshCaptcha();

    // 页面加载完成后聚焦到账号输入框
    const timer = setTimeout(() => {
      if (usernameInputRef.current) {
        usernameInputRef.current.focus();
      }
    }, 100);

    return () => clearTimeout(timer);
  }, []);

  // 当切换到账号登录标签时重新聚焦
  useEffect(() => {
    if (type === 'account' && usernameInputRef.current) {
      const timer = setTimeout(() => {
        usernameInputRef.current?.focus();
      }, 100);

      return () => clearTimeout(timer);
    }
  }, [type]);

  // 刷新验证码
  const refreshCaptcha = () => {
    const text = generateCaptcha();
    setCaptchaText(text);
    setCaptchaImage(drawCaptcha(text));
    setCaptchaError('');
  };

  const fetchUserInfo = async () => {
    const userInfo = await initialState?.fetchUserInfo?.();
    if (userInfo) {
      flushSync(() => {
        setInitialState((s) => ({
          ...s,
          currentUser: userInfo,
        }));
      });
    }
  };

  // 清空输入框
  const clearInputs = () => {
    form.setFieldsValue({
      username: '',
      password: '',
      captcha: '',
    });
    refreshCaptcha(); // 同时刷新验证码

    // 清空后重新聚焦到账号输入框
    if (usernameInputRef.current) {
      usernameInputRef.current.focus();
    }
  };

  const handleSubmit = async (values: API.LoginParams & { captcha?: string }) => {
    try {
      // 验证验证码
      if (values.captcha?.toUpperCase() !== captchaText) {
        setCaptchaError('验证码错误，请重新输入');
        clearInputs(); // 清空输入框
        return;
      }

      // 登录请求
      const res = await login({ ...values, type });
      if (res.code === 1) {
        const defaultLoginSuccessMessage = intl.formatMessage({
          id: 'pages.login.success',
          defaultMessage: '登录成功！',
        });
        message.success(defaultLoginSuccessMessage);

        localStorage.setItem('userInfo', JSON.stringify(res.data));
        localStorage.setItem('token', res.data.token);
        localStorage.setItem('userId', res.data.id);
        localStorage.setItem('menu', JSON.stringify(res.data.menu));

        await fetchUserInfo();
        const urlParams = new URL(window.location.href).searchParams;
        window.location.href = urlParams.get('redirect') || '/';
        return;
      }

      console.log(res);
      // 如果失败去设置用户错误信息
      setUserLoginState(res);

      // 登录失败时清空输入框
      clearInputs();

      // 显示错误提示
      message.error('账号或密码错误，请重新输入');

    } catch (error) {
      const defaultLoginFailureMessage = intl.formatMessage({
        id: 'pages.login.failure',
        defaultMessage: '登录失败，请重试！',
      });
      console.log(error);
      message.error(defaultLoginFailureMessage);

      // 发生错误时也清空输入框
      clearInputs();
    }
  };

  const { status, type: loginType } = userLoginState;

  return (
    <div className={styles.container} style={{ backgroundImage: `url(${background})`, backgroundSize: '100% 100vh' }}>
      <Helmet>
        <title>
          {intl.formatMessage({
            id: 'menu.login',
            defaultMessage: '登录页',
          })}
          {Settings.title && ` - ${Settings.title}`}
        </title>
      </Helmet>
      <Lang />
      <div style={{ display: 'flex', justifyContent: 'center', gap: '50px', marginTop: '20vh' }}>
        <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
          <img src={circle} alt="礼盒商城logo" style={{ width: '400px', height: '450px' }} />
        </div>
        <div
          style={{
            padding: '32px 0',
          }}
        >
          <LoginForm
            form={form} // 绑定form实例
            contentStyle={{
              minWidth: 280,
              maxWidth: '75vw',
            }}
            title="登录 礼盒商城"
            initialValues={{
              autoLogin: true,
            }}
            onFinish={async (values) => {
              await handleSubmit(values as API.LoginParams & { captcha?: string });
            }}
          >
            <Tabs
              activeKey={type}
              onChange={setType}
              centered
            />

            {status === 'error' && loginType === 'account' && (
              <LoginMessage
                content='账号或密码错误，请重新输入'
              />
            )}

            {captchaError && (
              <LoginMessage content={captchaError} />
            )}

            {type === 'account' && (
              <>
                <ProFormText
                  name="username"
                  fieldProps={{
                    size: 'large',
                    prefix: <UserOutlined />,
                    // 将输入框DOM引用赋值给ref
                    ref: usernameInputRef,
                  }}
                  placeholder='请输入账号'
                  rules={[
                    {
                      required: true,
                      message: (
                        <FormattedMessage
                          id="pages.login.username.required"
                          defaultMessage="请输入账号!"
                        />
                      ),
                    },
                  ]}
                />
                <ProFormText.Password
                  name="password"
                  fieldProps={{
                    size: 'large',
                    prefix: <LockOutlined />,
                    // 密码框回车时提交表单
                    onKeyDown: (e) => {
                      if (e.key === 'Enter') {
                        form.submit();
                      }
                    },
                  }}
                  placeholder='请输入密码'
                  rules={[
                    {
                      required: true,
                      message: (
                        <FormattedMessage
                          id="pages.login.password.required"
                          defaultMessage="请输入密码！"
                        />
                      ),
                    },
                  ]}
                />
                {/* 验证码输入框 */}
                <div className={styles.captchaContainer}>
                  <ProFormText
                    name="captcha"
                    fieldProps={{
                      size: 'large',
                      prefix: <LockOutlined />,
                      // 验证码框回车时提交表单
                      onKeyDown: (e) => {
                        if (e.key === 'Enter') {
                          form.submit();
                        }
                      },
                    }}
                    placeholder='请输入验证码'
                    rules={[
                      {
                        required: true,
                        message: '请输入验证码！',
                      },
                      {
                        len: 4,
                        message: '验证码长度为4位！',
                      },
                    ]}
                    onInput={(e) => {
                      if (captchaError) setCaptchaError('');
                    }}
                  />
                  <img
                    src={captchaImage}
                    alt="验证码"
                    className={styles.captchaImage}
                    onClick={refreshCaptcha}
                  />
                </div>
              </>
            )}

            {status === 'error' && loginType === 'mobile' && (
              <LoginMessage content="验证码错误" />
            )}
            {type === 'mobile' && (
              <>
                <ProFormText
                  fieldProps={{
                    size: 'large',
                    prefix: <MobileOutlined />,
                  }}
                  name="mobile"
                  placeholder={intl.formatMessage({
                    id: 'pages.login.phoneNumber.placeholder',
                    defaultMessage: '手机号',
                  })}
                  rules={[
                    {
                      required: true,
                      message: (
                        <FormattedMessage
                          id="pages.login.phoneNumber.required"
                          defaultMessage="请输入手机号！"
                        />
                      ),
                    },
                    {
                      pattern: /^1\d{10}$/,
                      message: (
                        <FormattedMessage
                          id="pages.login.phoneNumber.invalid"
                          defaultMessage="手机号格式错误！"
                        />
                      ),
                    },
                  ]}
                />
                <ProFormCaptcha
                  fieldProps={{
                    size: 'large',
                    prefix: <LockOutlined />,
                  }}
                  captchaProps={{
                    size: 'large',
                  }}
                  placeholder={intl.formatMessage({
                    id: 'pages.login.captcha.placeholder',
                    defaultMessage: '请输入验证码',
                  })}
                  captchaTextRender={(timing, count) => {
                    if (timing) {
                      return `${count} ${intl.formatMessage({
                        id: 'pages.getCaptchaSecondText',
                        defaultMessage: '获取验证码',
                      })}`;
                    }
                    return intl.formatMessage({
                      id: 'pages.login.phoneLogin.getVerificationCode',
                      defaultMessage: '获取验证码',
                    });
                  }}
                  name="captcha"
                  rules={[
                    {
                      required: true,
                      message: (
                        <FormattedMessage
                          id="pages.login.captcha.required"
                          defaultMessage="请输入验证码！"
                        />
                      ),
                    },
                  ]}
                  onGetCaptcha={async (phone) => {
                    const result = await getFakeCaptcha({
                      phone,
                    });
                    if (!result) {
                      return;
                    }
                    message.success('获取验证码成功！验证码为：1234');
                  }}
                />
              </>
            )}
            <div
              style={{
                marginBottom: 24,
              }}
            >
              <ProFormCheckbox noStyle name="autoLogin">
                <FormattedMessage
                  id="pages.login.rememberMe"
                  defaultMessage="记住密码"
                />
              </ProFormCheckbox>
            </div>
          </LoginForm>
        </div>
      </div>
      <Footer />
    </div>
  );
};

export default Login;
